import React, { useState } from "react";
import { Document, Page } from "react-pdf";
import { PDFDocument } from "pdf-lib";
import { saveAs } from "file-saver";
import {
  Button,
  Box,
  TextField,
  Typography,
  IconButton,
} from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import RotateLeftIcon from "@material-ui/icons/RotateLeft";
import SaveIcon from "@material-ui/icons/Save";
import CloudDownloadIcon from "@material-ui/icons/CloudDownload";

const useStyles = makeStyles((theme) => ({
  root: {
    width: 600,
    height: 800,
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    background: '#fff',
    paddingTop: theme.spacing(4),
  },
  input: {
    display: "none",
  },
  document: {
    marginTop: theme.spacing(2),
    border: `1px solid ${theme.palette.grey[400]}`,
    borderRadius: theme.shape.borderRadius,
    overflow: "hidden",
    boxShadow: theme.shadows[2],
  },
  page: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    height: 400,
  },
  actions: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    marginTop: theme.spacing(2),
    "& > *": {
      margin: theme.spacing(1),
    },
  },
  title: {
    marginBottom: theme.spacing(2),
  },
}));

function PdfEditor() {
  const classes = useStyles();
  const [pdf, setPdf] = useState(null);
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

  const onDocumentLoadSuccess = ({ numPages }) => {
    setNumPages(numPages);
  };

  const onFileChange = async (event) => {
    const file = event.target.files[0];
    const fileReader = new FileReader();

    fileReader.onload = async () => {
      const pdfDoc = await PDFDocument.load(fileReader.result);
      setPdf(pdfDoc);
    };

    fileReader.readAsArrayBuffer(file);
  };

  const handleRotate = async () => {
    const rotatedPdf = await pdf.rotatePages([pageNumber - 1], 90);
    setPdf(rotatedPdf);
  };

  const handleSave = async () => {
    const pdfBytes = await pdf.save();
    const blob = new Blob([pdfBytes], { type: "application/pdf" });
    saveAs(blob, "edited.pdf");
  };

  const handleConvertToWord = async () => {
    const pdfBytes = await pdf.save();
    const pdfDoc = await PDFDocument.load(pdfBytes);
    const docxBytes = await pdfDoc.saveAsBase64({ dataUri: true });
    const downloadLink = document.createElement("a");
    downloadLink.href = docxBytes;
    downloadLink.download = "converted.docx";
    downloadLink.click();
  };

  return (
    <div className={classes.root}>
      <Typography variant="h4" component="h1" className={classes.title}>
        Online PDF Editor
      </Typography>
      <Box>
        <input
          type="file"
          id="file-input"
          className={classes.input}
          onChange={onFileChange}
        />
        <label htmlFor="file-input">
          <Button variant="contained" component="span">
            Upload PDF
          </Button>
        </label>
      </Box>
      {pdf && (
        <Box className={classes.document}>
          <Document file={pdf} onLoadSuccess={onDocumentLoadSuccess}>
            <Page
              pageNumber={pageNumber}
              className={classes.page}
              width={600}
            />
          </Document>
          <Box className={classes.actions}>
            <IconButton aria-label="rotate" onClick={handleRotate}>
              <RotateLeftIcon />
            </IconButton>
            <IconButton aria-label="save" onClick={handleSave}>
              <SaveIcon />
            </IconButton>
            <IconButton aria-label="download" onClick={handleConvertToWord}>
              <CloudDownloadIcon />
            </IconButton>
            <TextField
              label="Page number"
              variant="outlined"
              type="number"
              value={pageNumber}
              onChange={(event) => setPageNumber(parseInt(event.target.value))}
              InputProps={{
                inputProps: { min: 1, max: numPages },
                style: { width: 80 },
              }}
              size="small"
            />
          </Box>
        </Box>
      )}
    </div>
  );
}

export default PdfEditor;
